from sanic.views import HTTPMethodView
from sanic.response import text,json
import time
from processing.other_func import ProToken,Sercret_all,Serialization,Random_id,date_format
import json as jn
import re
from processing.Sql_DataFrom import ProJosn
import requests


class typeAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:
            sql = """
                        insert into category(merchant_id,businessId,categoryDesc,categoryName,image,pid,status,ctime ) VALUES (%s,%s,%s,%s,%s,%s,%s,now())
                """
            db.insert(sql,(user_id,html_data['businessId'],html_data['categoryDesc'],html_data['categoryName'],html_data['image'],html_data['pid'] or '0',html_data['status']))
            return json({'code': 200, 'message': "添加成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/category/add', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)

class typeEdit(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:
            sql = """
                    update category set businessId=%s,categoryDesc=%s,categoryName=%s,status=%s,image=%s,ctime=now() where merchant_id=%s and id=%s
                """

            data = db.update(sql,(
                html_data['businessId'],
                html_data['categoryDesc'],
                html_data['categoryName'],
                html_data['status'],
                html_data['image'],
                user_id,
                html_data['id']
            ))

            return json({'code': 200,
                        'message': "编辑成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/category/edit', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class typeList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        try:
            sql = """
                    select id,businessId,categoryDesc,categoryName,image,pid,status,ctime from category where merchant_id=%s
                """
            sql += f" ORDER BY ctime DESC "
            data = db.find_all(sql,(user_id))
            if data:
                dataList = ProJosn(data, sql, 'sql').to_dict(orient='records')
            else:
                dataList = []
            return json({'code': 200,
                        'data':dataList,
                        'message': "请求成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/category/list', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)

class typeDelete(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = "delete from category where merchant_id=%s and id=%s"

            db.delete(sql, (user_id,int(html_data['id'])))

            return json({'code': 200,
                        'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/category/delete', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
        
class goodsAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            # 多门店
            businessId = jn.loads(html_data['businessId'])

            if len(businessId["BusinessList"]):
                for i in businessId['BusinessList']:
                    sql = """
                                insert into goods(merchant_id,businessId,distributionFee,effectDays,extJson,categoryId,goodsBeginTime,goodsEndingTime,goodsDetails,goodsDetailsJson,
                                goodsName,goodsSkuJson,goodsPrice,goodsStatus,goodsType,limitNum,memberPrice,packingFee,previewUrl,rewardIntegral,rotationImgsJson,
                                scribePrice,stockNum,contents,subtitle,keywords,status,
                                ctime ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now())
                        """
                    db.insert(sql,(
                        user_id,
                        jn.dumps(i) or '',
                        html_data['distributionFee'] or '0',
                        html_data['effectDays'] or '',
                        html_data['extJson'] or '0',  # 0是不推荐   1是推荐
                        html_data['categoryId'] or '0', # id为0则没有分类
                        html_data['goodsBeginTime'] or '2023-12-18 18:00:00',
                        html_data['goodsEndingTime'] or '2023-12-18 18:00:00',
                        html_data['goodsDetails'] or '',
                        html_data['goodsDetailsJson'] or '',
                        html_data['goodsName'],  # 必须有名字
                        html_data['goodsSkuJson'] or '',
                        html_data['goodsPrice'] or '0', # 不填价格默认0
                        html_data['goodsStatus'] or '0', # 0下架  1上架
                        html_data['goodsType'] or '5', # 1-快递,2-自提,3-到店消费,4快递自提都支持 5全部支持
                        html_data['limitNum'] or '', # 默认是无限
                        html_data['memberPrice'] or '', # 会员价 默认无
                        html_data['packingFee'] or '', #
                        html_data['previewUrl'] or '', # 预览
                        html_data['rewardIntegral'] or '', # 赠送积分
                        html_data['rotationImgsJson'] or '', # 轮播图
                        html_data['scribePrice'] or '', # 划线价格
                        html_data['stockNum'] or '', # 库存
                        html_data['contents'] or '', # 富文本
                        html_data['subtitle'] or '', #
                        html_data['keywords'] or '1', # 排序
                        html_data['status'] or 'normal'
                    ))
            else:
                sql = """
                                            insert into goods(merchant_id,businessId,distributionFee,effectDays,extJson,categoryId,goodsBeginTime,goodsEndingTime,goodsDetails,goodsDetailsJson,
                                            goodsName,goodsSkuJson,goodsPrice,goodsStatus,goodsType,limitNum,memberPrice,packingFee,previewUrl,rewardIntegral,rotationImgsJson,
                                            scribePrice,stockNum,contents,subtitle,keywords,status,
                                            ctime ) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now())
                                    """
                db.insert(sql, (
                    user_id,
                    '',
                    html_data['distributionFee'] or '0',
                    html_data['effectDays'] or '',
                    html_data['extJson'] or '0',  # 0是不推荐   1是推荐
                    html_data['categoryId'] or '0',  # id为0则没有分类
                    html_data['goodsBeginTime'] or '2023-12-18 18:00:00',
                    html_data['goodsEndingTime'] or '2023-12-18 18:00:00',
                    html_data['goodsDetails'] or '',
                    html_data['goodsDetailsJson'] or '',
                    html_data['goodsName'],  # 必须有名字
                    html_data['goodsSkuJson'] or '',
                    html_data['goodsPrice'] or '0',  # 不填价格默认0
                    html_data['goodsStatus'] or '0',  # 0下架  1上架
                    html_data['goodsType'] or '5',  # 1-快递,2-自提,3-到店消费,4快递自提都支持 5全部支持
                    html_data['limitNum'] or '',  # 默认是无限
                    html_data['memberPrice'] or '',  # 会员价 默认无
                    html_data['packingFee'] or '',  #
                    html_data['previewUrl'] or '',  # 预览
                    html_data['rewardIntegral'] or '',  # 赠送积分
                    html_data['rotationImgsJson'] or '',  # 轮播图
                    html_data['scribePrice'] or '',  # 划线价格
                    html_data['stockNum'] or '',  # 库存
                    html_data['contents'] or '',  # 富文本
                    html_data['subtitle'] or '',  #
                    html_data['keywords'] or '1',  # 排序
                    html_data['status'] or 'normal'
                ))
            return json({'code': 200, 'message': "添加成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/add', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class goodsEdit(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json

        try:
            """
            businessId=%s,distributionFee=%s,effectDays=%s,extJson=%s,categoryId=%s,goodsBeginTime=%s,goodsEndingTime=%s,
                    goodsDetails=%s,goodsDetailsJson=%s,goodsName=%s,goodsSkuJson=%s,goodsPrice=%s,goodsStatus=%s,goodsType=%s,limitNum=%s,memberPrice=%s,
                    packingFee=%s,previewUrl=%s,rewardIntegral=%s,rotationImgsJson=%s,scribePrice=%s,stockNum=%s,contents=%s,subtitle=%s,keywords=%s,ctime=now()
        """
            sql = """
                    update goods set businessId=%s,distributionFee=%s,effectDays=%s,extJson=%s,categoryId=%s,goodsBeginTime=%s,goodsEndingTime=%s,
                    goodsDetails=%s,goodsDetailsJson=%s,goodsName=%s,goodsSkuJson=%s,goodsPrice=%s,goodsStatus=%s,goodsType=%s,limitNum=%s,memberPrice=%s,
                    packingFee=%s,previewUrl=%s,rewardIntegral=%s,rotationImgsJson=%s,scribePrice=%s,stockNum=%s,contents=%s,subtitle=%s,keywords=%s,ctime=now()
                    where merchant_id=%s and id=%s
                """

            db.update(sql,(
                html_data['businessId'] or '',
                html_data['distributionFee'] or '0',
                html_data['effectDays'] or '',
                html_data['extJson'] or '0',  # 0是不推荐   1是推荐
                html_data['categoryId'] or '0', # id为0则没有分类
                html_data['goodsBeginTime'] or '2023-12-18 18:00:00',
                html_data['goodsEndingTime'] or '2023-12-18 18:00:00',
                html_data['goodsDetails'] or '',
                html_data['goodsDetailsJson'] or '',
                html_data['goodsName'],  # 必须有名字
                html_data['goodsSkuJson'] or '',
                html_data['goodsPrice'] or '0', # 不填价格默认0
                html_data['goodsStatus'] or '0', # 0下架  1上架
                html_data['goodsType'] or '5', # 1-快递,2-自提,3-到店消费,4快递自提都支持 5全部支持
                html_data['limitNum'] or '', # 默认是无限
                html_data['memberPrice'] or '', # 会员价 默认无
                html_data['packingFee'] or '', #
                html_data['previewUrl'] or '', # 预览
                html_data['rewardIntegral'] or '', # 赠送积分
                html_data['rotationImgsJson'] or '', # 轮播图
                html_data['scribePrice'] or '', # 划线价格
                html_data['stockNum'] or '', # 库存
                html_data['contents'] or '', # 富文本
                html_data['subtitle'] or '', #
                html_data['keywords'] or '', # 排序

                user_id,
                html_data['id']
            ))
            return json({'code': 200, 'message': "编辑成功!"})

        except Exception as error:
            print(error)
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/edit', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class goodsList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = """
                    select id,distributionFee,businessId,effectDays,extJson,categoryId,goodsBeginTime,goodsEndingTime,goodsDetails,goodsDetailsJson,
                    goodsSkuJson,goodsPrice,goodsStatus,goodsType,limitNum,goodsName,memberPrice,packingFee,previewUrl,rewardIntegral,rotationImgsJson,
                    scribePrice,stockNum,contents,keywords,status,subtitle,ctime
                    from goods where merchant_id=%s
                """
            sql += f" ORDER BY ctime DESC "
            data = db.find_all(sql,(user_id))
            if data:
                header = ['id','distributionFee', 'businessId', 'effectDays', 'extJson', 'categoryId', 'goodsBeginTime',
                        'goodsEndingTime', 'goodsDetails', 'goodsDetailsJson',
                        'goodsSkuJson', 'goodsPrice', 'goodsStatus', 'goodsType', 'limitNum', 'goodsName', 'memberPrice',
                        'packingFee', 'previewUrl', 'rewardIntegral', 'rotationImgsJson',
                        'scribePrice', 'stockNum', 'contents', 'keywords', 'status', 'subtitle','ctime']
                dataList = ProJosn(data, header, 'list').to_dict(orient='records')
            else:
                dataList = []
            return json({'code': 200,
                        'data':dataList,
                        'message': "请求成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/list', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class goodsDelete(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = "delete from goods where merchant_id=%s and id=%s"

            db.delete(sql, (user_id, html_data['id']))

            return json({'code': 200,
                        'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/goods/delete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)

class businessAdd(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:
            sql = """
                        insert into business(merchant_id,businessName,businessId,plugsConfigJson,otherConfigJson,status,ctime ) VALUES (%s,%s,%s,%s,%s,%s,now())
                """
            db.insert(sql,(user_id,html_data['businessName'],Random_id(32,"B"),html_data['plugsConfigJson'],html_data['otherConfigJson'],html_data['status']))
            return json({'code': 200, 'message': "添加成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/business/add', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)

class businessList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        pageNum = int(request.args.get('pageNum'))
        pageSize = int(request.args.get('pageSize'))
    
        try:
            sql = """
                    select id,merchant_id,businessName,businessId,plugsConfigJson,otherConfigJson,status,ctime from business where merchant_id=%s
                """
            sql += f" ORDER BY ctime DESC "
            # 分页pageNum
            if pageNum == 1:
                sql += f" LIMIT {pageSize} "
            else:
                sql += f" LIMIT {pageNum * pageSize - pageSize},{pageNum * pageSize} "
            data = db.find_all(sql, (user_id))



            if data:
                dataList = ProJosn(data, sql, 'sql').to_dict(orient='records')
            else:
                dataList = []

            return json({'code': 200,'data':dataList,'message': "请求成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/business/list', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class businessDel(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = "delete from business where merchant_id=%s and id=%s"

            db.delete(sql, (user_id, html_data['id']))

            return json({'code': 200,
                        'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/business/delete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)
class businessEdit(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        sql = """
                update business set plugsConfigJson=%s,businessName=%s,status=%s,ctime=now() where merchant_id=%s and id=%s
            """

        db.update(sql,(
            html_data['plugsConfigJson'],
            html_data['businessName'],
            html_data['status'],
            user_id,
            html_data['id']
        ))

        return json({'code': 200,'message': "编辑成功!"})
class placeAnOrder(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json
        order_id = Random_id(32,'ORDER')
        try:
            sql = """
                        insert into goods_order(merchant_id,order_id,business_id,wechat_openid,wechatNickname,wechatavatar,wechatphone,goods_id,goods_sku,order_type,paypal_type,total_money,goods_money,status,ctime,utime) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,now(),now())
                """
            db.insert(sql,(user_id,order_id,html_data['business_id'],html_data['wechat_openid'],html_data['wechatNickname'],html_data['wechatavatar'],
                        html_data['wechatphone'],html_data['goods_id'],html_data['goods_sku'],html_data['order_type'],html_data['paypal_type'],
                        html_data['total_money'],html_data['goods_money'],'normal'))

            return json({'code': 200, 'message': "下单成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/order/placeAnOrder', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)
class orderList(HTTPMethodView):
    async def get(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip

        html_data = request.json

        try:
            sql = """
                    select id,order_id,business_id,wechat_openid,wechatNickname,wechatavatar,wechatphone,goods_id,goods_sku,order_type,paypal_type,total_money,goods_money,status,ctime,utime from goods_order where merchant_id=%s
                """
            sql += f" ORDER BY utime DESC "
            data = db.find_all(sql, (user_id))

            if data:
                dataList = ProJosn(data, sql, 'sql').to_dict(orient='records')
            else:
                dataList = []

            return json({'code': 200,'data':dataList,'message': "请求成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/order/list', error))
            data = {
                'code':500,
                'message':'后端报错!'
            }
            return json(data)

class orderDel(HTTPMethodView):
    async def post(self, request):
        db = request.app.ctx.db
        # 获取用户列表
        user_id = request.app.ctx.user_id
        client_ip = request.ip
        html_data = request.json
        try:
            sql = "delete from goods_order where merchant_id=%s and id=%s"

            db.delete(sql, (user_id, html_data['id']))

            return json({'code': 200,
                        'message': "删除成功!"})

        except Exception as error:
            error_sql = 'insert into error_log(visit_ip,error_path,error_content,create_time ) VALUES (%s,%s,%s,now())'
            db.insert(error_sql, (client_ip, '/commodity/order/delete', error))
            data = {
                'code': 500,
                'message': '后端报错!'
            }
            return json(data)